import { ElMessage } from 'element-plus'
import { isObject, isString, isNumber, isArray } from './type'
import router from '@/router'

// 判断用户是否开启了动画减弱功能
export function isPrefersReducedMotion() {
  if (window.matchMedia) {
    return window.matchMedia('(prefers-reduced-motion)').matches === true
  }
  return false
}

// 转驼峰式命名
export function toCamelCase(str) {
  return str.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase())
}

// 动态加载css
export function loadCSS(url) {
  const link = document.createElement('link')
  link.rel = 'stylesheet'
  link.href = url
  link.onerror = () => {
    ElMessage.error(`Failed to load CSS from ${url}`)
  }
  document.head.appendChild(link)
}

// 全屏操作
export function toggleFullScreen(element = document.documentElement) {
  if (!element) return

  const documentObj = document
  const fullScreenFunctions = {
    enter:
      element.requestFullscreen ||
      element.msRequestFullscreen ||
      element.mozRequestFullScreen ||
      element.webkitRequestFullscreen,
    exit:
      documentObj.exitFullscreen ||
      documentObj.msExitFullscreen ||
      documentObj.mozCancelFullScreen ||
      documentObj.webkitExitFullscreen,
  }

  const isFull = !!(
    documentObj.webkitIsFullScreen ||
    documentObj.mozFullScreen ||
    documentObj.msFullscreenElement ||
    documentObj.fullscreenElement
  )

  if (isFull) {
    fullScreenFunctions.exit && fullScreenFunctions.exit.call(documentObj)
  } else {
    fullScreenFunctions.enter && fullScreenFunctions.enter.call(element)
  }
}

/**
 * @description 获取不同路由模式所对应的 url + params
 * @returns {string}
 */
export function getUrlWithParams() {
  const routerMode = router.history.current.mode
  const url = {
    hash: location.hash.substring(1),
    history: location.pathname + location.search,
  }
  return url[routerMode]
}

/**
 * @description 根据svg路径将svg转换为临时的图片url
 * @returns {string} svgPath
 */
export async function convertSvgToImage(svgPath) {
  const svgString = await fetch(svgPath).then((response) => response.text())
  const image = new Image()

  image.src = 'data:image/svg+xml;base64,' + btoa(encodeURIComponent(svgString))

  return image
}

/**
 * @description 复制文本到剪贴板
 * @param {any} text
 * @returns {any} svgPath
 */
export function copyToClipboard(text) {
  if (navigator.clipboard && window.isSecureContext) {
    return navigator.clipboard
      .writeText(text)
      .then(() => {
        console.log('复制成功')
      })
      .catch((err) => {
        console.error('复制失败', err)
      })
  } else {
    // 兼容旧版本浏览器
    const textArea = document.createElement('textarea')
    textArea.value = text
    textArea.style.position = 'fixed'
    textArea.style.top = 0
    textArea.style.left = 0
    textArea.style.width = '2em'
    textArea.style.height = '2em'
    textArea.style.padding = 0
    textArea.style.border = 'none'
    textArea.style.outline = 'none'
    textArea.style.boxShadow = 'none'
    textArea.style.background = 'transparent'
    document.body.appendChild(textArea)
    textArea.select()

    try {
      document.execCommand('copy')
      console.log('复制成功')
    } catch (err) {
      console.error('复制失败', err)
    }
  }
}

/**
 * @description 防抖函数
 * @param {function} fn 需要执行的函数
 * @param {number} delay 延迟执行时间
 * @param {function} immediate 是否立即执行
 * @returns {fn}
 */
export function debounce(fn, delay, immediate = false) {
  let timer = null

  return function (...args) {
    const context = this
    const later = () => {
      timer = null
      !immediate && fn.apply(context, args)
    }

    const callNow = immediate && !timer
    clearTimeout(timer)
    timer = setTimeout(later, delay)

    callNow && fn.apply(context, args)
  }
}

// 解析excel时间
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (isObject(time) || isArray(time)) {
    date = time
  } else {
    // 此处也可以使用+time直接转换
    if (isString(time)) {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari：https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (isNumber(time) && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
